package com.xp.basic.heima.nio.work;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;


public class TestWorkNio {

    // 一个 boss boss只管连接
    // 多个 work work 管理读取和写入

    // Boss线程
    public static void main(String[] args) throws IOException {

        ServerSocketChannel bossChannel = ServerSocketChannel.open();
        Selector bossSelector = Selector.open();

        bossChannel.configureBlocking(false);
        bossChannel.bind(new InetSocketAddress(8080));
        //注册感兴趣的连接事件
        bossChannel.register(bossSelector, SelectionKey.OP_ACCEPT);

        int workerCount = 2;
        //初始化两个
        Worker[] workers = new Worker[workerCount];
        workers[0] = new Worker("worker-0");
        workers[1] = new Worker("worker-1");
        AtomicInteger atomicInteger = new AtomicInteger(0);

        while (true){
            int select = bossSelector.select();
            if (select == 0) {
                continue;
            }
            Iterator<SelectionKey> iterator = bossSelector.selectedKeys().iterator();
            if (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                iterator.remove();

                //连接事件
                if (selectionKey.isAcceptable()) {
                    System.out.println("监听到连接事件");
                    SocketChannel workChannel = bossChannel.accept();

                    // 取模就是 round-r
                    Worker worker = workers[(atomicInteger.getAndIncrement() % workerCount)];
                    System.out.println("---- before registry  work : "+worker.name);
                    worker.registry(workChannel);
                    //唤醒selector一次，像我这种写法，是不用唤醒的，因为selector 永远再 registry 之后
//                    worker.selector.wakeup();
                    System.out.println("---- after registry  work : "+worker.name);

                }
            }
        }
    }

    static class Worker implements Runnable{

        SocketChannel socketChannel;
        Selector      selector;

        Thread        thread;
        /**
         * worker 名称
         */
        String        name;

        volatile  boolean  isCreate = false;

        public Worker(String name) {
            this.name = name;
        }

        /***
         * 这个方法是外部调用的
         * @param sc
         * @throws IOException
         */
        void registry(SocketChannel sc) throws IOException {

            if(!isCreate){
                selector = Selector.open();
                socketChannel = sc;
                sc.configureBlocking(false);
                sc.register(selector,SelectionKey.OP_READ);

                thread = new Thread(this,name);
                thread.start();

                isCreate = true;
            }
        }

        /**
         * Runs this operation.
         */
        @Override
        public void run() {

            try {
                while (true){
                    //阻塞等待事件
                    int select = selector.select();
                    if (select == 0 ) continue;
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        iterator.remove();
                        //可读事件
                        if (selectionKey.isReadable()) {
                            SocketChannel channel = (SocketChannel) selectionKey.channel();
                            ByteBuffer byteBuffer = ByteBuffer.allocate(16);
                            System.out.println(name + "收到可读事件 -- - - - - 准备读取 ------");
                            int read = channel.read(byteBuffer);
                            System.out.println(name + "读取字节 ------  "+read);
                            //可写事件
                        } else if (selectionKey.isWritable()) {
                            System.out.println(name + "收到可写事件 -- - - - -");

                        }

                        //必须处理掉这个事件，要么这个事件就一直在这
//                        selectionKey.cancel();

                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
